import 'package:flt_telephony_info/flt_telephony_info.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:permission_handler/permission_handler.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/my/recharge.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/api.dart';
import 'package:qgchat/http/models/goodsModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:tobias/tobias.dart' as tobias;

/**
 * 充值页面
 * page充值
 */

class Recharge extends StatefulWidget {
  @override
  _RechargeState createState() => _RechargeState();
}

class _RechargeState extends State<Recharge> {
  int rechargeIndex; // 充值下标
  int paymentMethodIndex; // 支付方式(0:支付宝, 1:微信)
  GoodsModel onGoodsModel; // 充值金额
  int userId;

// hook-------------------------------------------------------------------------

  @override
  void initState() {
    super.initState();

    rechargeIndex = 0;
    paymentMethodIndex = 1;

    fluwx.weChatResponseEventHandler.listen((res) {
      if (res is fluwx.WeChatPaymentResponse && res.isSuccessful) {
        print('支付成功：extData ${res.extData} type ${res.type}');
        apkChannel();
        showToast('支付成功');
        state(context, "user").userInfo();
      }
    });
  }

  @override
  void reassemble() {
    setState(() {});
    super.reassemble();
  }

// function---------------------------------------------------------------------

  // 充值记录
  void _rechargeRecord() {
    goPage(context, '/rechargeRecord', param: {
      'id': userId,
    });
  }

  // 立即充值
  void _rechargeClick() {
    UserApis.payment('${onGoodsModel.id}', "$paymentMethodIndex").then((res) {
      switch (paymentMethodIndex) {
        // 微信
        case 0:
          print(res['data']);
          fluwx.payWithWeChat(
            appId: "${res['data']['appid']}",
            partnerId: "${res['data']['partnerid']}",
            prepayId: "${res['data']['prepayid']}",
            packageValue: "${res['data']['package']}",
            nonceStr: "${res['data']['noncestr']}",
            timeStamp: res['data']['timestamp'],
            sign: "${res['data']['sign']}",
          );
          break;
        // 支付宝
        case 1:
          _aliPay(res['data']);
          break;
        default:
      }
    });
  }

  // 支付宝支付
  void _aliPay(String orderInfo) async {
    Map payRes;
    try {
      payRes = await tobias.aliPay(orderInfo);
      String resultStatus = payRes['resultStatus'];
      if (resultStatus == '9000') {
        showToast('支付成功');
        apkChannel();
        state(context, "user").userInfo();
      } else if (resultStatus == '4000') {
        showToast('支付失败');
      } else {
        showToast('${payRes['memo']}');
      }
    } on Exception catch (e) {
      payRes = {};
    }
  }

  // 渠道功能
  apkChannel() {
    switch (Config.apkChannel) {
      case ApkChannel.baidu:
        baiduOrder();
        break;
      default:
    }
  }

  //百度支付成功回调
  baiduOrder() async {
    PermissionHandler()
        .requestPermissions([PermissionGroup.phone]).then((res) async {
      final price = double.parse(onGoodsModel.price) * 1000;
      TelephonyInfo info = await FltTelephonyInfo.info;
      final anid = info.meid;
      CommonApis.baiduOrder(anid, "$price");
    });
  }

// widget-----------------------------------------------------------------------

  /// appbar
  Widget appbar() {
    return AppBar(
      leading: new IconButton(
        icon: new Icon(
          Icons.arrow_back_ios,
          color: Colors.black,
          size: px(36),
        ),
        onPressed: () => Navigator.of(context).pop(),
      ),
      centerTitle: true,
      elevation: 1,
      title: Text(
        '充值',
        style: TextStyle(
            fontSize: px(34),
            color: col('000000'),
            fontWeight: FontWeight.bold),
      ),
      actions: <Widget>[
        Center(
          child: Container(
            height: px(100),
            child: FlatButton(
              padding: EdgeInsets.all(px(0)),
              onPressed: _rechargeRecord,
              child: Text(
                '充值记录',
                style: TextStyle(
                  fontSize: px(34),
                  color: col('5640c6'),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 金币余额
  Widget goldBalance() {
    return Container(
      width: w100(context),
      height: px(320),
      padding: EdgeInsets.symmetric(horizontal: px(30)),
      margin: EdgeInsets.only(top: px(20)),
      child: Stack(
        children: <Widget>[
          Image.asset('assets/images/rechargeBg.png'),
          Container(
            width: w100(context),
            height: px(320),
            padding: EdgeInsets.symmetric(horizontal: px(50), vertical: px(40)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '金币余额',
                  style: TextStyle(
                    fontSize: px(34),
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  'Balance of gold COINS',
                  style: TextStyle(
                    fontSize: px(30),
                    color: Colors.white,
                    fontWeight: FontWeight.w300,
                  ),
                ),
                stateBuilder(context, 'user', (user) {
                  UserState userState = (user as UserState);
                  userId = userState.info.id;
                  return Text(
                    '${userState.info.gold}',
                    style: TextStyle(
                      fontSize: px(88),
                      color: Colors.white,
                      height: 1.7,
                    ),
                  );
                }),
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 充值金币
  Widget topUpGoldCoins() {
    RechargeBloc bloc = BlocProvider.of<RechargeBloc>(context);

    Widget _topUpGoldCoinsItem(
        String name, String money, int index, GoodsModel item) {
      return StreamBuilder(
        stream: bloc.rechargeIndexStream,
        initialData: bloc.rechargeIndex,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == index) {
            onGoodsModel = item;
            return Container(
              width: px(216),
              height: px(144),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(px(12)),
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    col('a96fff'),
                    col('7c5bff'),
                  ],
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '$name',
                    style: TextStyle(
                      fontSize: px(34),
                      color: Colors.white,
                    ),
                  ),
                  Text(
                    '￥$money 元',
                    style: TextStyle(
                      fontSize: px(26),
                      color: col('bec1c5'),
                    ),
                  ),
                ],
              ),
            );
          }
          return GestureDetector(
            onTapDown: (_) {
              bloc.changeGoldIndex(index);
            },
            child: Container(
              width: px(216),
              height: px(144),
              decoration: BoxDecoration(
                color: col('edeff2'),
                borderRadius: BorderRadius.circular(px(12)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '$name',
                    style: TextStyle(
                      fontSize: px(34),
                      color: col('303133'),
                    ),
                  ),
                  Text(
                    '￥$money 元',
                    style: TextStyle(
                      fontSize: px(26),
                      color: col('bec1c5'),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      );
    }

    return Container(
      width: w100(context),
      padding: EdgeInsets.symmetric(horizontal: px(30)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: px(40)),
            child: Text(
              '充值金币',
              style: TextStyle(
                fontSize: px(26),
                color: col('303133'),
                fontWeight: FontWeight.bold,
                height: 1.2,
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: px(40)),
            child: StreamBuilder(
              stream: bloc.rechargeStream,
              initialData: bloc.rechargeDefault,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                List<GoodsModel> list = (snapshot.data as List<GoodsModel>);
                return Wrap(
                  spacing: px(20),
                  runSpacing: px(20),
                  children: list.asMap().keys.map<Widget>((int index) {
                    GoodsModel item = list[index];
                    return _topUpGoldCoinsItem(
                        item.name, item.price, index, item);
                  }).toList(),
                );
              },
            ),
          )
        ],
      ),
    );
  }

  /// 选择支付方式
  Widget paymentMethod() {
    /// 是否选中样式
    Widget _selected(int index) {
      if (paymentMethodIndex == index) {
        return Image.asset('assets/images/icon/selected.png');
      } else {
        return Container(
          width: px(40),
          height: px(40),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(px(20)),
              border: Border.all(
                color: col('edeff2'),
                width: px(2),
              )),
        );
      }
    }

    return Container(
      width: w100(context),
      margin: EdgeInsets.only(top: px(60)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.symmetric(horizontal: px(30)),
            child: Text(
              '选择支付方式',
              style: TextStyle(
                fontSize: px(26),
                color: col('303133'),
                fontWeight: FontWeight.bold,
                height: 1.2,
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: px(10)),
            child: Column(
              children: <Widget>[
                /// 支付宝支付
                Container(
                  child: FlatButton(
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      setState(() {
                        paymentMethodIndex = 1;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: px(30)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            height: px(104),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: px(44),
                                  height: px(44),
                                  margin: EdgeInsets.only(right: px(14)),
                                  child: Image.asset(
                                      'assets/images/icon/alipay.png'),
                                ),
                                Text(
                                  '支付宝支付',
                                  style: TextStyle(
                                    fontSize: px(34),
                                    color: col('303133'),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            width: px(40),
                            height: px(40),
                            margin: EdgeInsets.only(right: px(30)),
                            child: _selected(1),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),

                /// 微信支付
                Container(
                  child: FlatButton(
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      setState(() {
                        paymentMethodIndex = 0;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: px(30)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            height: px(104),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: px(44),
                                  height: px(44),
                                  margin: EdgeInsets.only(right: px(14)),
                                  child: Image.asset(
                                      'assets/images/icon/wxpay.png'),
                                ),
                                Text(
                                  '微信支付',
                                  style: TextStyle(
                                    fontSize: px(34),
                                    color: col('303133'),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            width: px(40),
                            height: px(40),
                            margin: EdgeInsets.only(right: px(30)),
                            child: _selected(0),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 立即充值
  Widget rechargeButton() {
    return Container(
      width: w100(context),
      margin: EdgeInsets.only(top: px(66)),
      alignment: Alignment.center,
      child: Container(
        width: px(600),
        height: px(96),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(px(48)),
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [col('6f56ff'), col('ac70ff')],
            )),
        child: FlatButton(
            onPressed: _rechargeClick,
            padding: EdgeInsets.all(0),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(px(48)))),
            child: Text(
              '立即充值',
              style: TextStyle(
                fontSize: px(36),
                color: Colors.white,
              ),
            )),
      ),
    );
  }

  /// tips
  Widget tips() {
    return Container(
      width: w100(context),
      margin: EdgeInsets.only(top: px(40), bottom: px(50)),
      alignment: Alignment.center,
      child: Text(
        '注：充值金额不可退还和返现',
        style: TextStyle(
          fontSize: px(22),
          color: col('bfc2cc'),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appbar(),
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              /// 金币余额
              goldBalance(),

              /// 充值金币
              topUpGoldCoins(),

              /// 选择支付方式
              paymentMethod(),

              /// 立即充值
              rechargeButton(),

              /// tips
              tips(),
            ],
          ),
        ),
      ),
    );
  }
}
